package com.psct.social;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.psct.social.SocialManager.OnBindListener;
import com.tencent.weibo.api.TAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;

/**
 * 腾讯微博
 * 
 * @author zjingchuan
 * 
 */
public class TenceAccount extends SocialAccount {

	public static final String TENCE_REDIRECTURI = "http://www.qq.com";
	public static final String TENCE_CONSUMER_KEY = "801266644";
	public static final String TENCE_CLIENTSECRET = "267381b8dd37de800b93a86dfeb728c8";
	public static final int REQUEST_CODE = 11;

	@Override
	public void bind(Context context, OnBindListener listener) {
		this.listener = listener;
		OAuthV2 oAuth = new OAuthV2(TENCE_REDIRECTURI);
		oAuth.setClientId(TENCE_CONSUMER_KEY);
		oAuth.setClientSecret(TENCE_CLIENTSECRET);
		Intent intent = new Intent(context, OAuthV2AuthorizeWebView.class);// ����Intent��ʹ��WebView���û���Ȩ
		intent.putExtra("oauth", oAuth);
		((Activity) context).startActivityForResult(intent, REQUEST_CODE);

	}

	@Override
	public void unBind(Context context) {
		SocialAccountKeeper.removeTenceInfo(context);

	}

	@Override
	public void sendMessage(Context context, String content, String picPath,SendResultListener resultListener) {
		/*
		正确的json返回结果：

		{errcode : 0,msg : ok,ret : 0,data:{id : ,time : ,seqid : xxx}
		错误的json返回结果：

		{ret:"1",errcode:"1",msg:"error clientip"}*/
		
		TAPI tAPI = new TAPI(OAuthConstants.OAUTH_VERSION_2_A);
		OAuthV2 oAuthV2 = SocialAccountKeeper.getTenceOAuth(context);
		if (oAuthV2 == null)
			return;
		try {
			String result = "";
			if (TextUtils.isEmpty(picPath)) {
				result = tAPI.add(oAuthV2, "json", content, "127.0.0.1");
			} else {
				result = tAPI.addPic(oAuthV2, "json", content, "127.0.0.1", picPath);
			}
			Log.v("social", "发送腾讯微博返回结果"+result);
			if(resultListener==null)
				return;
			Gson gson = new Gson();
			Res res = gson.fromJson(result, new TypeToken<Res>() {}.getType());
			if(res.ret.equals("0")) {
				//TODO 发送成功
				resultListener.onSendOK();
			}else {
				//TODO 发送失败
				resultListener.onSendErr(res.msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			//TODO 网络异常
			if(resultListener!=null)
			resultListener.onNetErr();
		}finally {
			tAPI.shutdownConnection();
		}
	}

	class Res{
		public String errcode,ret,msg;
		public List<Data> data;
		class Data{
			public int id;
			public String time;
			public String seqid;
		}
	}
}
